package com.rrqs.activity;

import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.bumptech.glide.Glide;
import com.litesuits.http.request.content.multi.MultipartBody;
import com.litesuits.http.request.content.multi.StringPart;
import com.rrqs.MessageEvents;
import com.rrqs.activity.adapter.ExceptionDialogAdapter;
import com.rrqs.activity.adapter.ShopdetAdapter;
import com.rrqs.activity.common.Common;
import com.rrqs.activity.common.Const;
import com.rrqs.activity.data.GetAbnormalReasonBean;
import com.rrqs.activity.data.MainNumData;
import com.rrqs.activity.data.OrderDetailBean;
import com.rrqs.activity.data.OrderdetailData;
import com.rrqs.activity.data.OrderdetailSite;
import com.rrqs.activity.data.PostAbnormalBean;
import com.rrqs.activity.data.QiangDanData;
import com.rrqs.activity.data.ZhuanDanData;
import com.rrqs.frame.JsonProcessHelper;
import com.rrqs.net.AsyncHttpClient;
import com.rrqs.net.HttpResponseListener;
import com.rrqs.util.MyApplication;
import com.rrqs.utils.JsonUtils;
import com.rrqs.views.MyListView;
import com.zadtek.xmqishi.R;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.rrqs.activity.common.Const.TOURL;

/**
 * 订单详情界面
 *
 * @author Administrator
 */
public class OrderDetailNewActivity extends BaseActivity {
    Context mContext;
    int type = 0;
    String  main_id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        mContext = this;

        try {
            findViewById(R.id.iv_back).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

        findViewById(R.id.sv).setVisibility(View.GONE);
        findViewById(R.id.bottom_1).setVisibility(View.GONE);
        findViewById(R.id.bottom_2).setVisibility(View.GONE);

        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null) {
             main_id = bundle.getString("mainid");
            type = bundle.getInt("type",0);
            requestData(main_id);
        }
    }

    private void requestData(String main_id) {

        AsyncHttpClient httpClient = new AsyncHttpClient(com.rrqs.util.MyApplication.getInstace());
        SharedPreferences sp = com.rrqs.util.MyApplication.getInstace().getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
        String uid = sp.getString("uid", "");
        com.litesuits.http.request.content.multi.MultipartBody body = new com.litesuits.http.request.content.multi.MultipartBody();
        body.addPart(new StringPart("emp_id", uid));
        body.addPart(new StringPart("ince", "get_order_infos"));
        body.addPart(new StringPart("main_id", main_id));
        httpClient.post(TOURL, body, new HttpResponseListener() {
            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);
            }

            @SuppressWarnings("unchecked")
            @Override
            public void onSuccess(String status, String result) {
                super.onSuccess(status, result);
                try {
                    OrderDetailBean bean = JsonUtils.json2Class(result, OrderDetailBean.class);
                    refreshView(bean);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        });
    }

    private void refreshView(final OrderDetailBean bean) {

        findViewById(R.id.sv).setVisibility(View.VISIBLE);
        setText(R.id.order_status, bean.getOrder().getOrder_status());
        if ("已接单".equals(bean.getOrder().getOrder_status())
                || "已取货".equals(bean.getOrder().getOrder_status())){
            setText(R.id.reas_time,  bean.getOrder().getReas_time());
            setText(R.id.shengyu, bean.getOrder().getShengyu());
        } else if ("已送达".equals(bean.getOrder().getOrder_status())){
            setText(R.id.reas_time,  bean.getOrder().getOrder_status());
            setText(R.id.shengyu, bean.getOrder().getReas_time());
        } else if ("待确认".equals(bean.getOrder().getOrder_status())){
            findViewById(R.id.ll_1).setVisibility(View.GONE);
            findViewById(R.id.reas_time).setVisibility(View.GONE);
        }
        if ("待确认".equals(bean.getOrder().getOrder_status()) || "".equals(bean.getOrder().getOrder_status())){
            findViewById(R.id.bottom_1).setVisibility(View.GONE);
            findViewById(R.id.bottom_2).setVisibility(View.VISIBLE);
            if (type == 1){
                setText(R.id.tv_confirm, "确认(系统)");
                findViewById(R.id.tv_zhuan).setVisibility(View.VISIBLE);
            } else {
                setText(R.id.tv_confirm, "确认(调度)");
                findViewById(R.id.tv_zhuan).setVisibility(View.GONE);
            }
            if ("".equals(bean.getOrder().getOrder_status())){
                findViewById(R.id.ll_2).setVisibility(View.GONE);
            }
        } else {
            findViewById(R.id.bottom_1).setVisibility(View.VISIBLE);
            findViewById(R.id.bottom_2).setVisibility(View.GONE);
        }

        setText(R.id.tv_shop_name, bean.getOrder().getAmin_name());
        setText(R.id.tv_shop_addr, bean.getOrder().getSend_address());
        setText(R.id.tv_song_addr, bean.getOrder().getGet_address());
        setText(R.id.jiedan_time, bean.getOrder().getJiedan_time());

        LinearLayout ll_product_container = findViewById(R.id.ll_product_container);
        addGoodsToView(ll_product_container, bean.getOrder().getGoods_info());

        setText(R.id.tv_note, bean.getOrder().getPostscript());
        setText(R.id.tv_order_no, bean.getOrder().getOrder_number());
        setText(R.id.tv_add_time, bean.getOrder().getAdd_time());
        setText(R.id.yaoqiu, bean.getOrder().getYaoqiu());
        setText(R.id.pay_name, bean.getOrder().getPay_name());
        setText(R.id.order_status, "");
        setText(R.id.order_status, "");

        findViewById(R.id.tv_look_road).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("已取货".equals(bean.getOrder().getOrder_status())
                        || "已送达".equals(bean.getOrder().getOrder_status())){
                    Intent intent = new Intent(mContext, MyMapLocation.class);
                    intent.putExtra("lat", bean.getOrder().getUser_lat());
                    intent.putExtra("lng", bean.getOrder().getUser_lng());
                    mContext.startActivity(intent);
                } else if("骑手已接单".equals(bean.getOrder().getOrder_status())
                        || "待骑手确认".equals(bean.getOrder().getOrder_status())){
                    Intent intent = new Intent(mContext, MyMapLocation.class);
                    intent.putExtra("lat", bean.getOrder().getShang_lat());
                    intent.putExtra("lng", bean.getOrder().getShang_lng());
                    mContext.startActivity(intent);
                }
            }
        });



        findViewById(R.id.tv_copy).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager cmb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                cmb.setText(bean.getOrder().getOrder_number());

                Toast.makeText(OrderDetailNewActivity.this, "已复制", Toast.LENGTH_SHORT).show();
            }
        });

        findViewById(R.id.tv_guke).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bean.getOrder().getUser_phone() != null && !bean.getOrder().getUser_phone().equals("")) {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse("tel:" + bean.getOrder().getUser_phone()));
                    if (intent.resolveActivity(getPackageManager()) != null) {
                        startActivity(intent);
                    }
                }
            }
        });

        findViewById(R.id.tv_shangjia).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bean.getOrder().getMain_phone() != null && !bean.getOrder().getMain_phone().equals("")) {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse("tel:" + bean.getOrder().getMain_phone()));
                    if (intent.resolveActivity(getPackageManager()) != null) {
                        startActivity(intent);
                    }
                }
            }
        });

        findViewById(R.id.tv_confirm).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                AsyncHttpClient httpClient = new AsyncHttpClient(MyApplication.getInstace());

                SharedPreferences sp = com.rrqs.util.MyApplication.getInstace().getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
                String uid = sp.getString("uid", "");

                MultipartBody body = new MultipartBody();
                body.addPart(new StringPart("emp_id", uid));
                body.addPart(new StringPart("order_id", ""+main_id));
                body.addPart(new StringPart("ince", "qs_qiang_new"));
                httpClient.post("http://xmpc.zadtek.com/mobile/Qs/index", body, new HttpResponseListener() {
                    @Override
                    public void onFailure(Throwable error) {
                        super.onFailure(error);

                    }

                    @SuppressWarnings("unchecked")
                    @Override
                    public void onSuccess(String status, String result) {
                        super.onSuccess(status, result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            Log.i("CYX","转单"+jsonObject);
                        }catch (Exception e){

                        }
                        QiangDanData resp = JsonUtils.json2Class(result,QiangDanData.class);
                        if ( "1".equals(resp.getStatus())){
                            Toast.makeText(OrderDetailNewActivity.this, "确认成功", Toast.LENGTH_SHORT).show();
                            finish();
                        }  else {
                            Toast.makeText(OrderDetailNewActivity.this, resp.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });

        findViewById(R.id.tv_zhuan).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                AsyncHttpClient httpClient = new AsyncHttpClient(MyApplication.getInstace());

                SharedPreferences sp = com.rrqs.util.MyApplication.getInstace().getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
                String uid = sp.getString("uid", "");

                MultipartBody body = new MultipartBody();
                body.addPart(new StringPart("emp_id", uid));
                body.addPart(new StringPart("order_id", ""+main_id));
                body.addPart(new StringPart("ince", "get_qishi_timelong"));
                httpClient.post("http://xmpc.zadtek.com/mobile/Qs/index", body, new HttpResponseListener() {
                    @Override
                    public void onFailure(Throwable error) {
                        super.onFailure(error);

                    }

                    @SuppressWarnings("unchecked")
                    @Override
                    public void onSuccess(String status, String result) {
                        super.onSuccess(status, result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            Log.i("CYX","转单"+jsonObject);
                        }catch (Exception e){

                        }
                        ZhuanDanData resp = JsonUtils.json2Class(result,ZhuanDanData.class);
                        if (resp.getStatus() == 1){
                            Toast.makeText(OrderDetailNewActivity.this, "转单成功", Toast.LENGTH_SHORT).show();
                            finish();
                        }  else {
                            Toast.makeText(OrderDetailNewActivity.this, resp.getFail(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });

    }

    private void addGoodsToView(LinearLayout ll_product_container, List<OrderDetailBean.Goods_info> goods) {
        for (int i = 0; i < goods.size(); i++) {
            OrderDetailBean.Goods_info item = goods.get(i);
            View v = getLayoutInflater().inflate(R.layout.submit_product_item, null);
            ImageView img = (ImageView) v.findViewById(R.id.iv_product_img);
            TextView title = (TextView) v.findViewById(R.id.tv_product_title);
            TextView num = (TextView) v.findViewById(R.id.tv_product_num);

            Glide.with(this).load(item.getImage()).into(img);
            title.setText(item.getFname());
            num.setText("x " + item.getQuantity());
            ll_product_container.addView(v);
        }
    }

    private void setText(int id, String str) {
       try{
           ((TextView) findViewById(id)).setText(str);
       } catch (Exception e){
           e.printStackTrace();
       }
    }
}
